home *** CD-ROM | disk | FTP | other *** search
/ Amiga Aktuell / Amiga Aktuell.iso / classes / range.py < prev    next >
Text File  |  1996-09-05  |  2KB  |  72 lines

  1. # Example of a generator: re-implement the built-in range function
  2. # without actually constructing the list of values.  (It turns out
  3. # that the built-in function is about 20 times faster -- that's why
  4. # it's built-in. :-)
  5.  
  6.  
  7. # Wrapper function to emulate the complicated range() arguments
  8.  
  9. def range(*a):
  10.     if len(a) == 1:
  11.         start, stop, step = 0, a[0], 1
  12.     elif len(a) == 2:
  13.         start, stop = a
  14.         step = 1
  15.     elif len(a) == 3:
  16.         start, stop, step = a
  17.     else:
  18.         raise TypeError, 'range() needs 1-3 arguments'
  19.     return Range(start, stop, step)
  20.     
  21.  
  22. # Class implementing a range object.
  23. # To the user the instances feel like immutable sequences
  24. # (and you can't concatenate or slice them)
  25.  
  26. class Range:
  27.  
  28.     # initialization -- should be called only by range() above
  29.     def __init__(self, start, stop, step):
  30.         if step == 0:
  31.             raise ValueError, 'range() called with zero step'
  32.         self.start = start
  33.         self.stop = stop
  34.         self.step = step
  35.         self.len = max(0, int((self.stop - self.start) / self.step))
  36.  
  37.     # implement `x` and is also used by print x
  38.     def __repr__(self):
  39.         return 'range' + `self.start, self.stop, self.step`
  40.  
  41.     # implement len(x)
  42.     def __len__(self):
  43.         return self.len
  44.  
  45.     # implement x[i]
  46.     def __getitem__(self, i):
  47.         if 0 <= i < self.len:
  48.             return self.start + self.step * i
  49.         else:
  50.             raise IndexError, 'range[i] index out of range'
  51.  
  52.  
  53. # Small test program
  54.  
  55. def test():
  56.     import time, __builtin__
  57.     print range(10), range(-10, 10), range(0, 10, 2)
  58.     for i in range(100, -100, -10): print i,
  59.     print
  60.     t1 = time.time()
  61.     for i in range(1000):
  62.         pass
  63.     t2 = time.time()
  64.     for i in __builtin__.range(1000):
  65.         pass
  66.     t3 = time.time()
  67.     print t2-t1, 'sec (class)'
  68.     print t3-t2, 'sec (built-in)'
  69.  
  70.  
  71. test()
  72.